package two.chapter_1.c1_3;

import java.util.Iterator;

/**
 * 先进先出
 * 对头出，对尾入
 * @param <Item>
 */
public class LinkedQueue<Item> implements Queue<Item> {

    private int size;
    private Node head;
    private Node tail;

    public LinkedQueue(){

    }
    public LinkedQueue(Queue<Item> q){
        int n=q.size();
        for (int i=0;i<n;i++){
            Item item=q.dequeue();
            enqueue(item);
            q.enqueue(item);
        }
    }

    public void enqueue(Item item){

        Node node =new Node(item);
        if (isEmpty()){
            tail=head=node;
        }else {
            tail.next=node;
            tail=node;
        }
        size++;

    }

    public Item dequeue(){

        if (isEmpty()){
           return null;
        }
        Node node=head;
        head=head.next;
        if (head==null){
            tail=null;
        }
        size--;
        return node.item;
    }


    @Override
    public boolean isEmpty() {
        return size()==0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<Item> iterator() {
        return new Iter();
    }


    private class Node{
        Item item;
        Node next;
        public Node(Item item){
            this.item=item;
        }
    }

    private class Iter implements Iterator<Item> {

        private Node next=head;
        @Override
        public boolean hasNext() {
            return next!=null;
        }

        @Override
        public Item next() {
            Item item= next.item;
            next=next.next;
            return item;
        }

        @Override
        public void remove() {

        }
    }
}
